import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-15
 * Time: 8:50
 */
public class TcpEchoClient {
    Socket socket = null;

    public TcpEchoClient(String serverIp, int serverPort) throws IOException {
        socket = new Socket(serverIp, serverPort);
    }

    public void start() {
        System.out.println("客户端启动");
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream();
             Scanner scannerConsole = new Scanner(System.in);
             Scanner scannerNetwork = new Scanner(inputStream);
             PrintWriter writer = new PrintWriter(outputStream)) {
            while (true) {
                System.out.print("->");

                //1、从控制台输入内容
                if (!scannerConsole.hasNext()) {
                    break;
                }
                String request = scannerConsole.next();
                //2、构造请求内容，发送请求给服务器
                writer.println(request);
                writer.flush();
                //3、接收响应
                String response = scannerNetwork.next();
                //4、把响应显示到控制台上
                System.out.println(response);

            }
        } catch(IOException e){
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();
    }
}

